﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using System.Windows.Media.Imaging;
using slTestingStreaming.Controls;
using System.Text;
using System.Collections.Generic;
using System.Net.Browser;
using System.Runtime.Serialization.Json;
using TweetStream.Extensions.Contracts;

namespace slTestingStreaming
{
	public partial class InlineHyperlink : UserControl
	{


		public InlineHyperlink()
		{
			// Required to initialize variables
			InitializeComponent();
		}

        public Grid DynamicControlsContainer { get; set; }


        LoadingCursor lc;

        #region LinkUri


        public Uri LinkUri
        {
            get { return (Uri)GetValue(LinkUriProperty); }
            set { SetValue(LinkUriProperty, value); }
        }

        public static readonly DependencyProperty LinkUriProperty =
            DependencyProperty.Register("LinkUri", typeof(Uri), typeof(InlineHyperlink), new PropertyMetadata(LinkUriPropertyChanged));

        private static void LinkUriPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
        {
            
            Uri u = (Uri)args.NewValue;
            try
            {
                foreach (var part in Model.ModelLocator.Instance.ExtensionManager.parts)
                {
                    string t = u.OriginalString;
                    t = part.RetrieveKey(t);
                    bool check = part.CheckIfAutoLoad(t);
                    if (check)
                    {
                        ((InlineHyperlink)obj).DoLoadingUpHyperlink(t, u);
                        part.InitControl(
                            new InitMessage()
                            {
                                DynamicControlsContainer = ((InlineHyperlink)obj).DynamicControlsContainer,
                                Key = t,
                                Url = u.OriginalString,
                                LoadingAnimation = (Storyboard)((InlineHyperlink)obj).lc.FindName("sbRotate"),
                                LoadingAnimationContainer = ((InlineHyperlink)obj).grdDynamicControls
                            }
                        );
                    }
                }
            }
            catch { }
        }
        #endregion


        #region DisplayLink

        public string DisplayLink
        {
            get { return (string)GetValue(DisplayLinkProperty); }
            set { SetValue(DisplayLinkProperty, value); }
        }

        public static readonly DependencyProperty DisplayLinkProperty =
            DependencyProperty.Register("DisplayLink", typeof(string), typeof(InlineHyperlink), new PropertyMetadata(DisplayLinkPropertyChanged));

        private static void DisplayLinkPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
        {
            string u = (string)args.NewValue;
            ((InlineHyperlink)obj).lblLink.Text = u;

            
        }
        #endregion

        private void lblLink_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            //StartLoadingUpHyperlink();

            Model.ModelLocator.Instance.TwitterManager.HyperlinkClicked(this.LinkUri);
        }


        private void StartLoadingUpHyperlink()
        {
            bool found = false;
            foreach (var part in Model.ModelLocator.Instance.ExtensionManager.parts)
            {
                string check = part.RetrieveKey(this.LinkUri.OriginalString);
                if (check != string.Empty)
                {
                    DoLoadingUpHyperlink(check, this.LinkUri);
                    found = true;
                    break;
                }
            }
            if (!found)
            {
                Model.ModelLocator.Instance.TwitterManager.HyperlinkClicked(this.LinkUri);
            }


        }

        private void DoLoadingUpHyperlink(string check, Uri uri)
        {
            loadingDynamicControlsStart();



        }

        void loadingDynamicControlsStart()
        {

            this.grdDynamicControls.Visibility = Visibility.Visible;
            lc = new LoadingCursor() { Width = 15, Height = 15 };
            this.grdDynamicControls.Height = 15;
            this.grdDynamicControls.Width = 15;
            this.grdDynamicControls.Children.Add(lc);
            lc.StartAnimation();
        }






        bool isExpanding = false;
        //private void lblLink_MouseEnter(object sender, MouseEventArgs e)
        //{
        //    //foreach (var part in Model.ModelLocator.Instance.ExtensionManager.parts)
        //    //{
        //    //    string u = ((InlineHyperlink)sender).LinkUri.OriginalString;
        //    //    u = part.DoCheck(u);
        //    //    bool check = part.DoCheckAutoLoad(u);

        //    //    if (check)
        //    //    {
        //    //        ((InlineHyperlink)sender).StartLoadingUpHyperlink();
        //    //    }

        //    //}
        //    return; // cant seem to get this to work....

        //    string test = this.LinkUri.OriginalString.ToLower();
        //    if (test.Contains("bit.ly") || test.Contains("is.gd") || test.Contains("tr.im") || test.Contains("tiny.url"))
        //    {
        //        if (isExpanding) return;

        //        //logic to expand
        //        var fetch = new List<string>();
        //        fetch.Add(test);


        //        Uri longUrlPleaseUri = GetLongUrlPleaseUri(fetch);


        //        bool httpResult = HttpWebRequest.RegisterPrefix("http://", WebRequestCreator.ClientHttp);
        //        bool httpsResult = HttpWebRequest.RegisterPrefix("https://", WebRequestCreator.ClientHttp);

        //        HttpWebRequest rq = (HttpWebRequest)WebRequestCreator.ClientHttp.Create(longUrlPleaseUri);
        //        rq.Method = "GET";

        //        rq.BeginGetResponse(
        //        new AsyncCallback(
        //           r =>
        //           {
        //               try
        //               {
        //                   WebResponse rs = rq.EndGetResponse(r);
        //                   using (Stream stream = rs.GetResponseStream())
        //                   {
        //                       using (StreamReader sr = new StreamReader(stream))
        //                       {
        //                           string responseText = sr.ReadToEnd();

        //                           using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(responseText)))
        //                           {
        //                               try
        //                               {
        //                                   DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Dictionary<object, object>));
        //                                   var t = (Dictionary<object, object>)serializer.ReadObject(ms);
        //                               }
        //                               catch (Exception ex){ }
        //                           }

        //                       }
        //                   }


        //               }
        //               catch (WebException ex)
        //               {

        //               }
        //           }), null);

        //        isExpanding = true;   
        //    }
        //}


        //private static Uri GetLongUrlPleaseUri(IEnumerable<String> shortUrls)
        //{
        //    // Single or multiple short URLs may be requested.             
        //    // http://www.longurlplease.com/api/v1.1?q=http://bit.ly/enAo&q=http://short.ie/bestxkcd

        //    var parameters = new StringBuilder();

        //    String delimiter = string.Empty;
        //    foreach (var url in shortUrls)
        //    {
        //        parameters.Append(delimiter).AppendFormat("q={0}", url);
        //        delimiter = "&";
        //    }

        //    return new Uri(string.Format("http://www.longurlplease.com/api/v1.1?{0}", parameters), UriKind.Absolute);
        //}

    }

}